package com.miniprogram.api.shiro.realm;

import com.miniprogram.api.service.*;
import com.miniprogram.bean.po.CustomerPermission;
import com.miniprogram.bean.po.CustomerRole;
import com.miniprogram.bean.po.CustomerUser;
import com.miniprogram.common.enums.CustomerUserStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 自定义Realm
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private ICustomerUserService iCustomerUserService;
    @Autowired
    private ICustomerRoleService iCustomerRoleService;
    @Autowired
    private ICustomerPermissionService iCustomerPermissionService;

    /**
     * 获取用户角色和权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        CustomerUser user = (CustomerUser) SecurityUtils.getSubject().getPrincipal();
        Integer userId = user.getId();

        System.out.println("用户" + userId + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        List<CustomerRole> roleList = iCustomerRoleService.findByUserId(userId);
        Set<String> roleSet = new HashSet<String>();
        for (CustomerRole r : roleList) {
            roleSet.add(r.getName());
        }
        simpleAuthorizationInfo.setRoles(roleSet);

        // 获取用户权限集
        List<CustomerPermission> permissionList = iCustomerPermissionService.findByUserId(userId);
        Set<String> permissionSet = new HashSet<String>();
        for (CustomerPermission p : permissionList) {
            permissionSet.add(p.getName());
        }
        simpleAuthorizationInfo.setStringPermissions(permissionSet);
        return simpleAuthorizationInfo;
    }

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        // 获取用户输入的用户名和密码
        Integer userId = (Integer) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        // 通过用户名到数据库查询用户信息
        CustomerUser user = iCustomerUserService.getById(userId);

        if (user == null) {
            throw new UnknownAccountException("用户不存在！");
        }
        if (!password.equals(user.getPassword())) {
            throw new IncorrectCredentialsException("用户名或密码错误！");
        }
        if (user.getStatus().equals(CustomerUserStatusEnum.FORBIDDEN.getCode())) {
            throw new LockedAccountException("账号已被锁定,请联系管理员！");
        }
        return new SimpleAuthenticationInfo(user, password, getName());
    }

}
